<?php
class ControllerSettingAutocomplete extends Controller {	
	
	public function template() {
		$json = array();

		if (isset($this->request->get['filter_name'])) {
			$this->load->model('setting/template');

			$data = array(
				'filter_name' => $this->request->get['filter_name'],
				'start'       => 0,
				'limit'       => 20
			);

			$templates = $this->model_setting_template->getTemplates($data);

			foreach ($templates as $template) {
				$json[] = array(
					'template_id'    => $template['template_id'],
					'name'         => html_entity_decode($template['name'], ENT_QUOTES, 'UTF-8'),
					'directory'         => html_entity_decode($template['directory'], ENT_QUOTES, 'UTF-8')
				);
			}
		}

		$sort_order = array();
			
		foreach ($json as $key => $value) {
			$sort_order[$key] = $value['name'];
		}

		array_multisort($sort_order, SORT_ASC, $json);

		$this->response->setOutput(json_encode($json));
	}

	public function templateDirectory(){
		$this->load->model('setting/image');

		$json = array();

		if (isset($this->request->get['filter_name'])) {
			$this->load->model('setting/template');

			if($this->restaurant->getRestaurantId() == null){
				$directories = glob(DIR_RESTAURANT . 'view/theme/*', GLOB_ONLYDIR);
			} else {
				$directories = glob(DIR_PORTAL . 'view/theme/*', GLOB_ONLYDIR);				
			}

			foreach ($directories as $directory) {
				$dirname = basename($directory);

				$length = strlen($this->request->get['filter_name']);
				if (substr($dirname, 0, $length) === $this->request->get['filter_name']) {
					if (file_exists(DIR_IMAGE . "templates/" . $dirname . ".png")) {
						$image = $this->model_setting_image->resize("/templates/" . $dirname . ".png", 200, 200);
					} else {
						$image = $this->model_setting_image->resize('no_image.jpg', 100, 100);
					}

					$json[] = array(
							'directory'    => $dirname,
							'image'		   => $image
					);
				}
			}
		}

		$sort_order = array();

		foreach ($json as $key => $value) {
			$sort_order[$key] = $value['directory'];
		}

		array_multisort($sort_order, SORT_ASC, $json);

		$this->response->setOutput(json_encode($json));
	}
	
}
?>